<script lang="ts">
  import { Badge, Tooltip } from 'svelte-5-ui-lib'
  import { FileCopyOutline, CheckOutline } from 'flowbite-svelte-icons'
  import { simpleRandomId } from '$lib/utils/textKit.svelte'

  type CopyParams = {
    text: string | Record<string, any> | (() => string)
    successText?: string
    copyIconClass?: string
    copiedIconClass?: string
    tips?: string
    recoverDuration?: number
  }

  // 接收 Props
  let {
    text,
    successText = 'Copied',
    copyIconClass = 'w-5 h-5 text-orange-300 dark:text-orange-400 hover:text-orange-600',
    copiedIconClass = 'w-5 h-5',
    tips = 'Copy',
    recoverDuration = 2000,
  }: CopyParams = $props()

  let isCopied = $state(false)

  const copy = async () => {
    try {
      let content = ''
      switch (typeof text) {
        case 'function':
          content = text()
          break
        case 'string':
          content = text
          break
        default:
          content = text = JSON.stringify(text, null, 4)
          break
      }

      // 现代浏览器方案
      await navigator.clipboard.writeText(content)

      isCopied = true
      setTimeout(() => (isCopied = false), recoverDuration)
    } catch (err) {
      console.error('复制失败:', err)
    }
  }

  const tipId: string = simpleRandomId()
</script>

<span id={tipId}>
  {#if tips}
    <Tooltip position="left" offset={6} triggeredBy="#{tipId}">{tips}</Tooltip>
  {/if}

  {#if isCopied}
    <Badge color="green">
      {successText}
      <CheckOutline class={copiedIconClass} />
    </Badge>
  {:else}
    <FileCopyOutline onclick={copy} class={copyIconClass} />
  {/if}
</span>
